package com.sduonline.isdapp.other;

import java.io.IOException;
import java.text.ParseException;

import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;

import com.sduonline.isdapp.config.AutoServiceTriggerConfig;
import com.sduonline.isdapp.service.AutoService;
import com.sduonline.isdapp.util.TimeUtil;

public class AutoServletTrigger {

	private static Thread thread = null;

	/**
	 * 自动获取文章的get方法的触发器，用这种方式实现AutoService自动获取从指定日期到现在日期文章。
	 */
	public void autoVisitAutoService() {

		String url = "http://202.194.14.197:8283/isdunews/AutoServlet";
		long st = AutoServiceTriggerConfig.st;
		long period = 24 * 60 * 60 * 2; // 2天的时间间隔
		long finalEt = AutoServiceTriggerConfig.et;

		long et = st + period;

		while (et < finalEt) {
			try {
				System.out.println("auto visit myself:st=" + TimeUtil.convertTo_yyyyMMdd(st + "000") + ",et="
						+ TimeUtil.convertTo_yyyyMMdd(et + "000"));
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			try {
				Jsoup.connect(url).data("st", st + "").data("et", et + "").method(Method.GET).timeout(5 * 1000)
						.execute();
				Thread.sleep(1000 * 60);// 1分钟反应时间
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			st = et;
			et = st + period;
		}

	}

	/**
	 * 将autoVisitArticlesWithinTime方法封装成thread
	 */
	public void startAutoVisitThread() {
		if (thread == null) {
			Runnable r = new Runnable() {

				@Override
				public void run() {
					autoVisitArticlesWithinTime();
				}
			};
			thread = new Thread(r);
		}

		thread.start();
	}

	public void stopAutoVisitThread() {
		if (thread != null) {
			Thread temp = thread;
			thread = null;
			temp.interrupt();
		}
	}

	/**
	 * 自动调用定时访问的接口
	 */
	private void autoVisitArticlesWithinTime() {

		AutoService as = new AutoService();
		long st = 1459440000;
		long period = 24 * 60 * 60 * 2; // 2天的时间间隔

		long et = st + period;

		while (et < System.currentTimeMillis()) {
			try {
				System.out.println("auto visit myself:st=" + TimeUtil.convertTo_yyyyMMdd(st + "000") + ",et="
						+ TimeUtil.convertTo_yyyyMMdd(et + "000"));
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			try {
				as.visitArticlesWithinTime(st + "", et + "");
				Thread.sleep(1000 * 60);// 1分钟反应时间
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			st = et;
			et = st + period;
		}

	}

	public static void main(String[] args) {
		new AutoServletTrigger().autoVisitAutoService();
	}
}